import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Select, Table, DatePicker, message, } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import moment from 'moment'
import { connect } from 'dva'
import {
  getOrders,
} from '@/services/distribution/order'
import {
  getToken, exportsExcel
} from '@/utils/utils'
import { router } from 'umi'

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const { RangePicker } = DatePicker
const columns = [
  {
    title: '序号',
    dataIndex: 'sort',
    key: 'sort',
    render(text, record, index){
      return <div>{index + 1}</div>
    }
  },
  {
    title: "订单号",
    dataIndex: "orderNo",
    key: "orderNo"
  },
  {
    title: "下单时间",
    dataIndex: "orderTime",
    key: "orderTime"
  },
  {
    title: "门店名称",
    dataIndex: "storeName",
    key: "storeName"
  },
  {
    title: "平台来源",
    dataIndex: "platFormName",
    key: "platFormName"
  },
  {
    title: "订单大类",
    dataIndex: "orderTypeName",
    key: "orderTypeName"
  },
  {
    title: "支付场景",
    dataIndex: "orderPaySceneName",
    key: "orderPaySceneName"
  },
  {
    title: "购买人",
    dataIndex: "purchaserName",
    key: "purchaserName"
  },
  {
    title: "购买电话",
    dataIndex: "purchaserPhoneNumber",
    key: "purchaserPhoneNumber"
  },
  {
    title: "订单金额",
    dataIndex: "actualPrice",
    key: "actualPrice"
  },
  {
    title: "订单状态",
    dataIndex: "platOrderStatusName",
    key: "platOrderStatusName"
  },
  {
    title: "支付状态",
    dataIndex: "payStatusName",
    key: "payStatusName"
  },
  {
    title: "操作",
    key: "action",
    dataIndex: 'action',
    render: (t, record) => <a onClick={() => router.push(`/distribution/orderDetails?orderNo=${record.orderNo}`)}>查看</a>
  }
];
const distributionPersonType = [{
  name: '员工',
  type: '0',
}, {
  name: '会员',
  type: '1',
}, {
  name: '渠道商',
  type: '2',
}]
const payrollStatus = [{
  name: '待返佣',
  type: '0'
}, {
  name: '已返佣',
  type: '1'
}]


const Order = props => {
  const { form, merchants, stores, dispatch, global, } = props
  const { platForms, payScenes, osTypes, orderTypes, payStatus, orderStatus, } = global
  const { getFieldDecorator } = form
  const [data, setData] = useState([])
  const [total, setTotalPage] = useState(null)
  const [rangeTime, setRangeTime] = useState(null)
  const [param, setParam] = useState({
    pageNo: 1,
    pageSize: 10,
  })
  useEffect(() => {
    init()
    dispatch({
      type: 'distribute/fetchMerchants'
    })
  }, [])

  const init = async (params = param) => {
    const res = await getOrders(params)
    setData(res.data)
    setTotalPage(res.total)
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)
      init({
        ...values,
      })
    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
    init()
  }
  // 查询条件
  const getFields = () => {
    return(
      <>
        <Col span={8}>
          <Form.Item label={`所属商户`}>
            {getFieldDecorator(`supplierId`, {})
              (<Select onChange={selectMerchant}>
                {
                  merchants && merchants.map(m => <Select.Option key={m.id} value={m.id}>{m.merchantName}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`所属门店`}>
            {getFieldDecorator(`storeId`, {})
              (<Select>
                {
                  stores && stores.map(m => <Select.Option key={m.id} value={m.id}>{m.name}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`订单号`}>
            {getFieldDecorator(`orderNo`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`商品名称`}>
            {getFieldDecorator(`goodsName`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`购买人名称`}>
            {getFieldDecorator(`purchaserName`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`分销人名称`}>
            {getFieldDecorator(`distributionPersonName`, {})
              (<Input />)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`分销人类型`}>
            {getFieldDecorator(`distributionPersonName`, {})
              (<Select>
                {
                  distributionPersonType.map(m => <Select.Option key={m.type} value={m.type}>{m.name}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`分佣状态`}>
            {getFieldDecorator(`distributionStatus`, {})
              (<Select>
                {
                  payrollStatus.map(m => <Select.Option key={m.type} value={m.type}>{m.name}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`操作系统`}>
            {getFieldDecorator(`osType`, {})
              (<Select>
                {
                  osTypes.map(m => <Select.Option key={m.value} value={m.value}>{m.label}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`部门`}>
            {getFieldDecorator(`department`, {})
              (<Select>
                {
                  // system.map(m => <Select.Option key={m.value} value={m.value}>{m.label}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`分组`}>
            {getFieldDecorator(`group`, {})
              (<Select>
                {
                  // system.map(m => <Select.Option key={m.value} value={m.value}>{m.label}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`平台来源`}>
            {getFieldDecorator(`platForm`, {})
              (<Select>
                {
                  platForms.map(m => <Select.Option key={m.value} value={m.value}>{m.label}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`订单类目`}>
            {getFieldDecorator(`orderType`, {})
              (<Select>
                {
                  orderTypes.map(m => <Select.Option key={m.value} value={m.value}>{m.label}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`支付场景`}>
            {getFieldDecorator(`orderPayScene`, {})
              (<Select>
                {
                  payScenes.map(m => <Select.Option key={m.value} value={m.value}>{m.label}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`订单状态`}>
            {getFieldDecorator(`platOrderStatus`, {})
              (<Select>
                {
                  orderStatus.map(m => <Select.Option key={m.value} value={m.value}>{m.label}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`支付状态`}>
            {getFieldDecorator(`payStatus`, {})
              (<Select>
                {
                  payStatus.map(m => <Select.Option key={m.value} value={m.value}>{m.label}</Select.Option>)
                }
              </Select>)}
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item label={`下单时间`}>
            {getFieldDecorator(`time`, {})
              (<RangePicker
                showTime
                format={'YYYY/MM/DD HH:mm:ss'}
                placeholder=''
                onOk={data => setRangeTime(data)}
              />)}
          </Form.Item>
        </Col>
      </>
    )
  }

  const selectMerchant = (val) => {
    dispatch({
      type: 'distribute/fetchStores',
      payload: {
        supplierId: val,
        pageSize: 999,
      }
    })
  }

  // 按钮处理
  const handleBtn = type => {
    if (data.length == 0 && type == 97) return message.warning('暂无导出数据！') 
    switch (type) {
      case 97:
       return exportsExcel({
         columns,
         data,
         title: '分销订单',
       })
      default:
        break;
    }
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {
      init({
        pageNo: page,
      })
    }
  }  

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table 
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowKey={record => record.id}
        pagination={pagination}
      />
    </PageHeaderWrapper>
    )
}

export default connect(({ distribute, global }) => ({
  merchants: distribute.merchants,
  stores: distribute.stores,
  global,
}))(Form.create()(Order))
